<template>  <!--该页面为从设备探索进入的历史探索测试记录页面-->
  <div>
    <el-breadcrumb separator="/"> <!--面包屑never-->
    <el-breadcrumb-item><i class="el-icon-s-home" style="margin-right: 15px;font-size: 16px"></i>工位配置</el-breadcrumb-item>
    </el-breadcrumb>
	  <div class="info">
      <!-- 暂无工位查询 -->
      <el-card shadow="always" class="cardPosition">
        <!-- <div slot="header" class="clearfix">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item class="roleInput" label="工位名称">
              <el-input v-model.trim="searchContent" placeholder="请输入工位名称" clearable  size="small"></el-input>
            </el-form-item>
            <el-form-item class="search" label="">
              <el-button size="small" @click="toSerach" style="float: right;" type="primary">查询</el-button>
            </el-form-item>
          </el-form> -->
        <!-- <el-row align="middle" type="flex">
          <div style="margin-right:10px;width: 60px;">
            <span style="align:center" >工位名称</span>
          </div>
          <el-col :span="4">
            <el-row>
              <el-input placeholder="请输入工位名称" clearable v-model="searchContent"  size="small"></el-input>
            </el-row>
          </el-col>
          <el-col :span="18">
          </el-col>
          <el-button type="primary"  @click="toSerach"  size="small">查询</el-button>
        </el-row> -->
        <!-- </div> -->
      <!-- </el-card>
      <el-card shadow="always" class="cardPosition"> -->
         <el-button type="text" class="global_add" :disabled="btnList.add" @click="dialogVisible = true" size="small" style="float:right; margin-right: 15px;margin-bottom: 5px;">+&nbsp;新增工位</el-button>
        <el-dialog
          title="新增工位"
          :visible.sync="dialogVisible"
          width="450px"
          >
          <el-form  label-width="120px" :model="newStation" :rules="rules" ref="newStation"  size="small">
            <el-form-item label="工位名称" prop="stationName">
              <el-input placeholder="请输入工位名称" v-model.trim="newStation.stationName" style="width: 90%" clearable></el-input>
            </el-form-item>
            <el-form-item label="负责人" prop="userId">
              <el-select v-model="newStation.userId" placeholder="请选择负责人" @change="getTelephoneOfNew" style="width: 90%" clearable>
                <el-option v-for="item in userList" :key="item.user_id" :label="item.nickname" :value="item.user_id" ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
              <el-input placeholder="请选择负责人" v-model="newStation.telephone" :disabled="true" style="width: 90%" clearable></el-input>
            </el-form-item>
            <!-- <el-form-item>
                  <el-form-item>
                    <div style="float: right">
                      <el-button @click="cancel">取消</el-button>
                      <el-button type="primary" @click="submitForm('newStation')">保存</el-button>
                    </div>
                  </el-form-item>
            </el-form-item> -->
          </el-form> 
          <span slot="footer" class="dialog-footer">
                      <el-button class="textBtn" @click="cancel"  size="small">取消</el-button>
                      <el-button type="primary" @click="submitForm('newStation')"  size="small">保存</el-button>
                    </span>
        </el-dialog>
        <el-table stripe v-loading="dataLoading" :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" border style="width: 100%">
          <el-table-column type="index" label="#" :index = '(index) =>{return (index + 1) + (currentPage - 1) * pagesize}' width="70" align="center"></el-table-column>
          <el-table-column align="center" prop="station_name" label="工位名称" :span="8"></el-table-column>
          <el-table-column align="center" prop="nickname" label="负责人" :span="8"></el-table-column>
          <el-table-column align="center" prop="telephone" label="联系电话" :span="8"></el-table-column>
          <el-table-column align="center" label="操作"  :span="8">
            <template slot-scope="scope">
              <el-button class="global_edit" @click="toEditStation(scope.$index, scope.row)" :disabled="btnList.edit" type="text" size="small" style="color:#6C59DD">编辑</el-button>
                
              <el-button class="global_delete" type="text" size="small" :disabled="btnList.delete" @click="toDeleteStation(scope.$index, scope.row)" style="color:#D9001B;"> 删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="pagination" background :current-page.sync="currentPage" :hide-on-single-page="showPagination" :page-size="pagesize" layout="prev, pager, next" :total="tableData.length"></el-pagination>
      </el-card>
      <el-dialog
                  title="编辑工位"
                  :visible.sync="editStationdialog"
                  width="450px"
                  >
                  <el-form  label-width="120px" :model="editStation" :rules="rules" ref="editStation"  size="small">
                    <el-form-item label="工位名称" prop="stationName">
                      <el-input placeholder="请输入工位名称" v-model.trim="editStation.stationName"  style="width: 90%" clearable></el-input>
                    </el-form-item>
                   <el-form-item label="负责人" prop="nickName">
                      <el-select v-model="editStation.userId" placeholder="请选择负责人" @change="getTelephoneOfEdit" style="width: 90%" clearable>
                        <el-option v-for="item in userList" :key="item.user_id" :label="item.nickname" :value="item.user_id" ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="联系电话" prop="telephone">
                      <el-input placeholder="请选择负责人" v-model="editStation.telephone" :disabled="true" style="width: 90%" clearable></el-input>
                    </el-form-item>
                    <!-- <el-form-item>
                      <div style="float: right">
                        <el-button @click="editStationdialog = false">取消</el-button>
                        <el-button type="primary" @click="submitEditForm('editStation')">保存</el-button>
                      </div>
                    </el-form-item> -->
                  </el-form> 
                    <span slot="footer" class="dialog-footer">
                      <el-button class="textBtn" @click="editStationdialog = false"  size="small">取消</el-button>
                      <el-button type="primary" @click="submitEditForm('editStation')"  size="small">保存</el-button>
                    </span>
                </el-dialog>
    </div>
  </div>
</template>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 引入需要用到的第三方nodejs库，如日期计算等
// 需要先通过npm安装第三方组件包，然后在代码中使用
// npm install xxx :settings="chartSettings"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import moment from 'moment';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import roleBtn from '../../public/means'
export default {
	data() {
		return {
      dialogVisible: false,
      editStationdialog:false,
      showPagination: true,     //分页显示
      currentPage: 1,           //从第几页开始显示
      pagesize: 10,              //每页多少行数据
      dataLoading: false,
      menu_id: 12,
      btnList: {
        add: false,
        edit: false,
        delete: false,
      },
      newStation:{
        stationName:'',
        nickName:'',
        userId:'',
        telephone:'',
      },
      editStation:{
        stationId:'',
        stationName:'',
        telephone:'',
        userId:'',
      },
      searchContent:'',
      rules:{
        userId:[{required: true, message: '请选择负责人', trigger: 'blur' }],
        stationName:[{required: true, message: '请输入工位名称', trigger: 'blur' }],
        telephone:[{required: true, message: '请输入联系电话', trigger: 'blur' }],
      },
      tableData: [],
      userList:[]
		};
	},
	methods: {
    submitForm(formName) {
      this.$refs.newStation.validate(valid => {
        console.log(valid);
        if(!valid) {
          return;
        }
        this.$message.closeAll();
      let check = true;
      if(this.newStation.stationName.indexOf(" ") !== -1 ){
        check = false;
        this.$message({ message: '工位名称不允许含有空格！', type: 'error', duration: 1000 });
      }else{
        for(let i = 0;i < this.tableData.length;i++){
          if(this.newStation.stationName == this.tableData[i].station_name){
            this.$message.closeAll();
            this.$message({ message: '工位名称不可重复！', type: 'error', duration: 1000 });
            check = false;
          }
        }
      } 
      if(check)
        this.saveNewStation();
      })
      
    },
    submitEditForm(formName,row){
      this.$refs.editStation.validate(valid => {
        console.log(valid);
        if(!valid) {
          return;
        }
         this.$message.closeAll();
      let check = true;
      if(this.editStation.stationName =="" ){
        this.$message({ message: '请输入正确的工位名称！', type: 'error', duration: 1000 });
        check = false;
      }else{
         for(let i = 0;i < this.tableData.length;i++){
            if (this.editStation.stationId !== this.tableData[i].station_id){
              if(this.editStation.stationName == this.tableData[i].station_name){
                  this.$message.closeAll();
                  this.$message({ message: '工位名称不可重复！', type: 'error', duration: 1000 });
                  check = false;
              }
            }
          }
      }

      if(check)
        this.saveEditStation();
      })
      
     
    },
    getSearchTableData(){  
    },
    toEditStation(index,row){
      this.editStationdialog=true;
      this.editStation.stationId=row.station_id;
      this.editStation.stationName=row.station_name;
      this.editStation.telephone=row.telephone;
      this.editStation.userId=row.user_id
    },
    handleClick(row) {
      console.log(row);
    },
    toSerach(){
    },
    getTelephoneOfNew(value){
      for(let i=0;i<this.userList.length;i++){
        if(value==this.userList[i].user_id){
          this.newStation.telephone=this.userList[i].telephone;
        }    
      }
    },
    getTelephoneOfEdit(value){
      for(let i=0;i<this.userList.length;i++){
        if(value==this.userList[i].user_id){
          this.editStation.telephone=this.userList[i].telephone;
        }    
      }
    },
    async getAllStation(){
      this.dataLoading = true;
      const ret = await this.$http.get("/stationManagement/getAllStation");
      this.tableData = ret.result;
      this.dataLoading = false;
    },
    async getAllUser(){
      const ret = await this.$http.get("/stationManagement/getAllUser");
      this.userList = ret.result;
    },
    //删除工位
    toDeleteStation(index,row){
      this.$confirm('确定删除该工位,此操作不可撤销', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(({ result }) => {
        if(!result){
					this.deleteStation(row.station_id);
				}
      }).catch(() => {
        });
    },
    //删除工位
    async deleteStation(stationId){
      let ret;
      const params = {
        'stationId': stationId,
      }
      ret = await this.$http.delete("/stationManagement/deleteStation",{params,});
      if(ret.code === 200&&ret.message == '删除成功'){
      this.$message({
          showClose: true,
          message: ret.message,
          type: 'success'
        });
      }
      if(ret.message === '该工位下存在设备，不允许删除！'){
      this.$message({
          showClose: true,
          message: ret.message,
          type: 'warning'
        });
      }
      this.getAllStation();
      
    },
    //修改工位
    async saveEditStation(){
      const params = {
        'stationId': this.editStation.stationId,
        'stationName': this.editStation.stationName,
        'userId': this.editStation.userId,
      };
      const ret = await this.$http.post("/stationManagement/saveEditStation",params);
        if(ret.code === 200){
        this.$message({
          showClose: true,
          message: '修改成功',
          type: 'success'
        });
      }
      this.$refs['editStation'].resetFields();
      this.editStationdialog = false;
      this.getAllStation();
},  //新增工位
    async saveNewStation(){
      const params = {
        userId: this.newStation.userId,
        stationName: this.newStation.stationName,
      };
      
      const ret = await this.$http.post("/stationManagement/saveNewStation",params);
      if(ret.code === 200){
      this.$message({
        showClose: true,
        message: '添加成功',
        type: 'success'
      });
      this.$refs['newStation'].resetFields();
      this.dialogVisible = false;
      this.getAllStation();
      }
    },
    cancel() {
      this.$refs.newStation.resetFields()
      this.dialogVisible = false
    }
  },
	mounted() {
    this.getAllStation();
    this.getAllUser();
	},
  async created() {
    const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      if(role_id){
      // 获取按钮权限状态
      let arr = await roleBtn.roleBtnList(role_id, this.menu_id)
      this.btnList = arr
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./StationManagement.scss";
</style>